package com.zhouzi.zhaoyang.ui.activity

import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.zhouzi.zhaoyang.R
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.base.BaseActivity
import com.zhouzi.zhaoyang.bean.AuthCodeBean
import com.zhouzi.zhaoyang.bean.BalancePaymentBean
import com.zhouzi.zhaoyang.bean.OrderDetailBean
import com.zhouzi.zhaoyang.mvp.p.NotSufficientFundsActivityPresenter
import com.zhouzi.zhaoyang.mvp.v.INotSufficientFundsActivityView
import com.zhouzi.zhaoyang.service.VoiceService
import com.zhouzi.zhaoyang.util.Calculator
import com.zhouzi.zhaoyang.util.FaceUtil
import com.zhouzi.zhaoyang.util.MyHttp
import kotlinx.android.synthetic.main.not_sufficient_funds_activity.*

class NotSufficientFundsActivity : BaseActivity(), INotSufficientFundsActivityView {
    override fun errorToken() {
        exitToLogin()
    }

    override fun payOrderSuccess(authCodeBean: AuthCodeBean) {
        val map = mutableMapOf(
            Pair("appid", authCodeBean.appid),
            Pair("mch_id", authCodeBean.mchId),
            Pair("store_id", authCodeBean.storeId),
            Pair("authinfo", authCodeBean.authinfo),
            Pair("payresult", "SUCCESS")
        )
        WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                finish()
            }
        })
        val intent = Intent(mContext, VoiceService::class.java)
        intent.putExtra("voiceStr", "交易成功")
        startService(intent)

        p.getOrder(authCodeBean.outTradeNo)

    }

    override fun payOrderFailed(msg: String, authCodeBean: AuthCodeBean) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()

        val map = mutableMapOf(
            Pair("appid", authCodeBean.appid),
            Pair("mch_id", authCodeBean.mchId),
            Pair("store_id", authCodeBean.storeId),
            Pair("authinfo", authCodeBean.authinfo),
            Pair("payresult", "ERROR")
        )
        WxPayFace.getInstance().updateWxpayfacePayResult(map, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                val intent = Intent(mContext, VoiceService::class.java)
                intent.putExtra("voiceStr", "交易失败")
                startService(intent)
            }
        })

    }

    override fun getAuthCodeSuccess(data: AuthCodeBean?) {

        data?.let {
            val map = mutableMapOf(
                Pair("appid", it.appid),
                Pair("mch_id", it.mchId),
                Pair("store_id", it.storeId),
                Pair("out_trade_no", it.outTradeNo),
                Pair("face_authtype", "FACEPAY"),
                Pair("authinfo", it.authinfo),
                Pair("ask_face_permit", "1"),
                Pair("total_fee", balancePaymentBean!!.totalFee.toString()),
                Pair("sub_appid", it.subAppId),
                Pair("sub_mch_id", it.subMchId),
                Pair("face_code_type", "1"),
                Pair("ask_ret_page", "1")//是否展示微信支付成功页，可选值："0"，不展示；"1"，展示
            )

            WxPayFace.getInstance().getWxpayfaceCode(map, object : IWxPayfaceCallback() {
                override fun response(p0: MutableMap<Any?, Any?>?) {
                    Handler(Looper.getMainLooper()).post {
                        if (FaceUtil().isSuccessInfo(p0)) {

                            Log.e("totalFee", balancePaymentBean!!.totalFee.toString())
                            val requestMap = mutableMapOf(
                                Pair("faceCode", p0?.get("face_code") as String),
                                Pair("deviceNo", deviceNo),
                                Pair("totalFee", balancePaymentBean!!.totalFee.toString()),
                                Pair("outTradeNo", data.outTradeNo)
                            )
                            if (!TextUtils.isEmpty(balancePaymentBean!!.memberFee.toString())) {
                                requestMap["memberFee"] = balancePaymentBean!!.memberFee.toString()
                            }
                            if (!TextUtils.isEmpty(balancePaymentBean!!.phone.toString())) {
                                requestMap["phone"] = balancePaymentBean!!.phone.toString()
                            }
                            p.payOrder(requestMap, data)
                        } else {
                            Toast.makeText(mContext, "获取faceCode失败，请稍后再试", Toast.LENGTH_SHORT)
                                .show()
                        }
                    }
                }
            })
        }

    }

    override fun getAuthCodeFailed(msg: String) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }

    override fun getOrderSuccess(orderDetail: OrderDetailBean?) {
        orderDetail?.let {
            App.instance().printProductInformation(orderDetail)
            MyHttp.report(orderDetail)
            Calculator.reset()
            var intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }

    }

    override fun getOrderFailed(msg: String?) {
        Toast.makeText(this, "getOrderFailed", Toast.LENGTH_SHORT)
    }

    override fun showLoadDialog() {
        loadDialog.show()
    }

    override fun dismissLoadDialog() {
        loadDialog.dismiss()

    }


    override fun getLayoutId(): Int {
        return R.layout.not_sufficient_funds_activity
    }


    private val balancePaymentBean: BalancePaymentBean?
        get() {
            var data = intent.getParcelableExtra<BalancePaymentBean>("data")
            return data
        }

    override fun initView() {
        var data = intent.getParcelableExtra<BalancePaymentBean>("data")
        tvApShowMoney.text = "原价：" + Calculator.fen2Yuan(data.totalFee!!.toLong()).toString()
        tvApShowVipMoney.text = "会员价：" + Calculator.fen2Yuan(data.memberFee!!.toLong()).toString()
        /*初始化刷脸*/
        WxPayFace.getInstance().initWxpayface(mContext, object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (FaceUtil().isSuccessInfo(p0)) {

                    } else {
                        Toast.makeText(mContext, "初始化失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })


        viewClick()
    }

    private fun viewClick() {


        tvApBtnBack1.setOnClickListener {
            finish()
        }

        tvApFacePay.setOnClickListener {
            getRawData()
        }

        tvMorePaymentMethods.setOnClickListener {
            var intent = Intent(this, PaymentMethodsActivity::class.java)
            intent.putExtra("data", balancePaymentBean)
            startActivity(intent)
        }
    }

    var p = NotSufficientFundsActivityPresenter()

    init {
        p.attachView(this)
    }


    var deviceNo = Build.SERIAL
    private fun getRawData() {
        /*获取rawData*/
        WxPayFace.getInstance().getWxpayfaceRawdata(object : IWxPayfaceCallback() {
            override fun response(p0: MutableMap<Any?, Any?>?) {
                Handler(Looper.getMainLooper()).post {
                    if (FaceUtil().isSuccessInfo(p0)) {
                        val rawData = p0?.get("rawdata").toString()
                        val map = mutableMapOf(
                            Pair("deviceNo", deviceNo),
                            Pair("rawdata", rawData)
                        )
                        p.getAuthCode(map)

                    } else {
                        Toast.makeText(mContext, "获取rawData失败，请稍后再试", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        p.detachView()
    }


}
